﻿using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System;
using Assets.Scripts;

public class UDPListener : MonoBehaviour
{
	public string ipAddress = "168.178.2.11";
	public int ConnectPort = 50000;
	public string recvStr;

	Socket socket;
	EndPoint clientEnd;
	IPEndPoint ipEnd;
	string sendStr;
	byte[] recvData = new byte[1024];
	byte[] sendData = new byte[1024];
	int recvLen;
	Thread connectThread;
	/// <summary>
	/// 初始化
	/// </summary>
	void InitSocket()
	{
		ipEnd = new IPEndPoint(IPAddress.Parse(ipAddress), ConnectPort);
		socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
		socket.Bind(ipEnd);
		//定义客户端
		IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
		clientEnd = (EndPoint)sender;
		print("等待连接数据");

		//开启一个线程连接
		connectThread = new Thread(new ThreadStart(SocketReceive));
		connectThread.Start();
	}
	/// <summary>
	/// 发送消息
	/// </summary>
	/// <param name="sendStr"></param>
	void SocketSend(string sendStr)
	{
		sendData = new byte[1024];
		sendData = Encoding.UTF8.GetBytes(sendStr);
		socket.SendTo(sendData, sendData.Length, SocketFlags.None, clientEnd);
	}

	private event Action callback = ()=> { };
	/// <summary>
	/// 接收消息
	/// </summary>
	void SocketReceive()
	{
		while (true)
		{
			byte[] recvData = new byte[1024];
			recvLen = socket.ReceiveFrom(recvData, ref clientEnd);
			recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen);

			StringBuilder builder = new StringBuilder();
			for (int i = 0; i < recvLen; i++)
			{
				builder.Append(recvData[i] + " ");
			}

			Debug.Log("收到得信息 \n" + builder.ToString() + " \n" + Thread.CurrentThread.ManagedThreadId);

			mainThreadContext.Post(new SendOrPostCallback(SocketReceive3), recvData);
		}
	}

	void SocketReceive3(object state)
	{
		recvData = state as byte[];
		Debug.LogError("mainThreadContext.Post : " + Thread.CurrentThread.ManagedThreadId);
		callback();
	}

	/// <summary>
	/// 关闭连接
	/// </summary>
	void SocketQuit()
	{
		//关闭线程
		if (connectThread != null)
		{
			connectThread.Interrupt();
			connectThread.Abort();
		}
		//最后关闭socket
		if (socket != null)
			socket.Close();
		Debug.LogWarning("断开连接");
	}

	/// <summary>
	/// 主线程的上下文，用来线程间通信的
	/// </summary>
	SynchronizationContext mainThreadContext;
	void Start()
	{
		mainThreadContext = SynchronizationContext.Current;
		InitSocket(); //在这里初始化server


		Debug.Log("主线程 ：" + Thread.CurrentThread.ManagedThreadId);
		callback += onReceiveData;
	}

	/// <summary>
	/// 收到消息的时候的回调
	/// </summary>
	private void onReceiveData()
	{
		//Debug.LogError("Callback : " + Thread.CurrentThread.ManagedThreadId);
		Vector2[] pos = UDPDataHelper.GetPosition(recvData);

		StringBuilder builder = new StringBuilder();
		foreach (var item in pos)
		{
			builder.AppendLine(item.ToString());
		}
		Debug.LogError(builder);
	}

	void OnApplicationQuit()
	{
		SocketQuit();
	}

}